from flask import current_app as app

from app.db.models.wass import ScanEvents

from . import BaseHandler
from .utils import get_warning_id
from ...libs.score import Score


class vulHostHandler(BaseHandler):

    def _check_response(self):
        self.response = self._get_events()
        if not self.response:
            app.logger.exception(f'[02]监测结果处理：task {self.task.id}任务结果为空')

    def _get_events(self):
        events = [item.to_mongo().to_dict() for item in ScanEvents.objects.filter(
            task_session_id=self.task.taskSessionId)]
        return events

    def parse_vul_host(self):
        data = {}
        for event in self.response:
            _event_name = event.get('event_name')
            _detail = event.get('detail', {})
            if _event_name == 'statistics':
                data[_event_name] = _detail
            else:
                _item = data.setdefault(_event_name, [])
                _item.append(_detail)
        return data

    def handle(self, **kwargs):
        severityMap = Score.severityMap
        event_dict = self.parse_vul_host()
        result = {"warnings": []}
        for item in event_dict.get("network_vuln", []):
            affects = item.get("host")
            warning = {
                "id": get_warning_id(
                    risk_title=item.get("source_id"),
                    task_type="hostVul",
                    url=affects,
                    job_id=self.task.jobId
                ),
                "level": severityMap.get(item["severity"], {}).get("level"),
                "levelName": severityMap.get(item["severity"], {}).get("zh_CN"),
                "title": item.get("name", {}).get("zh_cn"),
                "category": item.get("vuln_type", [{}])[0].get("zh_cn"),
                "affects": affects,
                "detailText": item.get("extra_detail"),
                "recommendation": item.get("recommendation", {}).get("zh_cn"),
                "impact": item.get("impact", {}).get("zh_cn"),
                "description": item.get("description", {}).get("zh_cn"),
                "reference": item.get("reference"),
                "cnvd": item.get("cnvd"),
                "foundAt": item.get("found_at"),
                "traffics": item.get("traffics"),
                "payload": item.get("payload"),
                "isResolved": False
            }
            result["warnings"].append(warning)
        return result
